/*
 * @version: 1.0
 * @Author: zhl
 * @Date: 2021-09-01 15:16:25
 * @LastEditors: zhl
 * @LastEditTime: 2022-01-27 15:28:23
 * @Description: file content
 */
#include "Server-APDU.h"
#include "check_code.h"

Server_APDU Server_APDU::c_instance;

Server_APDU::Server_APDU(){

}

Server_APDU::~Server_APDU(){

}
//
Server_APDU &Server_APDU::getInstance(){
    return c_instance;
}

int Server_APDU::packet(DLT698_FRAME& frame, DLT698_BUFFER& data, DLT698_BUFFER& resp){
    if((NULL == data.data) || (1 > data.len) || (NULL == resp.data)){
        return -1;
    }
    int offset = 0;
    int cs_start = 0;
    int hcs_offset = 0;
    //前导码
    if((0xFE == frame.lc[0]) && (0xFE == frame.lc[0]) && (0xFE == frame.lc[0]) && (0xFE == frame.lc[0])){
        memcpy(resp.data, frame.lc, sizeof(frame.lc));
        offset += sizeof(frame.lc);
        cs_start += sizeof(frame.lc);
    }
    //起始码
    memcpy(resp.data+offset, &(frame.sc), sizeof(frame.sc));
    offset += sizeof(frame.sc);
    cs_start += sizeof(frame.sc);
    //长度
    offset += sizeof(frame.l);
    //控制域
    frame.c.control_code.dir = 1;
    frame.c.control_code.sub_frame = data.segment;
    memcpy(resp.data+offset, &frame.c.value, sizeof(frame.c.value));
    offset += sizeof(frame.c.value);
    //地址域
    memcpy(resp.data+offset, &frame.sa_fc.value, sizeof(frame.sa_fc.value));
    offset += sizeof(frame.sa_fc.value);
    memcpy(resp.data+offset, frame.sa, frame.sa_fc.sa_fc.addr_len+1);
    offset += frame.sa_fc.sa_fc.addr_len+1;
    //客户机地址ca
    memcpy(resp.data+offset, &frame.ca, sizeof(frame.ca));
    offset += sizeof(frame.ca);
    //帧头校验 跳过
    hcs_offset = offset;
    offset += sizeof(uint16_t);
    //apdu
    if(1 == frame.c.control_code.sc){
        for(int i = 0; i < data.len; i++){
            resp.data[offset] = data.data[i]+frame.sbc;
            offset++;
        }
    }else{
        memcpy(resp.data+offset, data.data, data.len);
        offset += data.len;
    }
    //长度 需要加上尾部校验码的长度
    decltype(frame.l) ll = offset-cs_start+sizeof(uint16_t);
    memcpy(resp.data+cs_start, &ll, sizeof(frame.l));
    //帧头校验hcs
    uint16_t cs = get_fcs16(PPPINITFCS16, resp.data+cs_start, hcs_offset-cs_start);
    memcpy(resp.data+hcs_offset, &cs, sizeof(uint16_t));
    //帧校验fcs 赋值
    cs = get_fcs16(PPPINITFCS16, resp.data+cs_start, offset-cs_start);
    memcpy(resp.data+offset, &cs, sizeof(uint16_t));
    offset += sizeof(uint16_t);
    //结束符
    memcpy(resp.data+offset, &frame.em, sizeof(frame.em));
    offset += sizeof(frame.em);
    resp.len = offset;
    return offset;
}